package org.example.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.example.ServiceUtil;
import org.example.protocol.RpcRequest;
import org.example.protocol.RpcResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
@ChannelHandler.Sharable
public class RpcRequestHandler extends SimpleChannelInboundHandler<RpcRequest> {

    @Autowired
    private ServiceUtil serviceUtil;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRequest msg) throws Exception {
        // 根据类名获取到实例，并且通过反射调用到具体的方法
        Object rpcService = serviceUtil.getBean(Class.forName(msg.getClassName()));
        Class<?> clazz = rpcService.getClass();
        Method declaredMethod = clazz.getDeclaredMethod(msg.getMethodName(), msg.getParameterTypes());
        Object result = declaredMethod.invoke(rpcService, msg.getParameters());

        // 设置结果并返回
        RpcResponse rpcResponse = new RpcResponse();
        rpcResponse.setCode(200);
        rpcResponse.setResult(result);

        ctx.channel().writeAndFlush(rpcResponse);
    }
}
